using Framework;
using Framework.UI;
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Collections;


namespace Game {
    public sealed class LoadingPanel : UIPanel, ILoadingPanel
    {
        public Slider m_SliderLoading;
        public override EUILayer Layer { get { return EUILayer.Loading; } }

        private float m_LoadFirstHalf = 0.5f;
        private float m_LoadSpeed = 0.03f;
        private AsyncOperation m_LoadOperation;
        private float m_TargetProgress = 0.5f;
        private FrameworkAction m_CallBack = null;

        private void Start()
        {
            this.m_SliderLoading.value = 0;
            this.m_TargetProgress = this.m_LoadFirstHalf;
        }

        public void StartLoading(AsyncOperation loadOperation)
        {
            this.m_SliderLoading.value = 0;
            this.m_LoadOperation = loadOperation;
            StartCoroutine(this.RefreshLoading());
        }

        public void RefreshLoadingProgress(float progress)
        {
            if (Math.Abs(progress - 1) < 0.00001f)
            {
                this.m_TargetProgress = 0.9999999f;
            }
            else
            {
                this.m_TargetProgress = this.m_LoadFirstHalf + progress / (1 - this.m_LoadFirstHalf);
            }
        }

        public void SetEndCallBack(FrameworkAction callBack)
        {
            this.m_CallBack = callBack;
        }

        IEnumerator RefreshLoading()
        {
            AsyncOperation operation = this.m_LoadOperation;
            if (operation != null || operation.isDone)
            {
                while (operation.progress < 0.9f)
                {
                    while (this.m_SliderLoading.value < operation.progress * (this.m_LoadFirstHalf / 0.9f))
                    {
                        this.m_SliderLoading.value += this.m_LoadSpeed;
                        yield return new WaitForEndOfFrame();
                    }
                    yield return new WaitForEndOfFrame();
                }
                while (this.m_SliderLoading.value < 0.9999999f)
                {
                    while (this.m_SliderLoading.value < this.m_TargetProgress)
                    {
                        this.m_SliderLoading.value += this.m_LoadSpeed;
                        yield return new WaitForEndOfFrame();
                    }
                    yield return new WaitForEndOfFrame();
                }
            }
            this.m_CallBack?.Invoke();
        }

    }
}